package com.lzx.activity.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lzx.activity.entity.Voucher;
import com.lzx.activity.mapper.VoucherMapper;
import com.lzx.activity.service.VoucherService;
import com.lzx.common.utils.R;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzx
 * @since 2022-11-10
 */
@Service
public class VoucherServiceImpl extends ServiceImpl<VoucherMapper, Voucher> implements VoucherService {
    @Resource
    private VoucherMapper voucherMapper;

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    //添加秒杀劵
    @Override
    public R addVoucher(Voucher voucher) {
        voucherMapper.insert(voucher);
        //保存秒杀库存到redis中
        stringRedisTemplate.opsForValue().set("secKill:stock:" + voucher.getId(), voucher.getStock().toString());
        return R.ok().message("添加成功");
    }

    //根据活动id获取优惠券
    @Override
    public R getVoucherById(Integer activityId) {
        QueryWrapper<Voucher> wrapper = new QueryWrapper<>();
        wrapper.eq("activity_id", activityId);
        List<Voucher> list = voucherMapper.selectList(wrapper);
        return R.ok().data("list", list);
    }

    //修改优惠券
    @Override
    public R updateVoucher(Voucher voucher) {
        voucherMapper.updateById(voucher);
        return R.ok().message("修改成功");
    }

    //上架或下架优惠券
    @Override
    public R deleteVoucher(Long id, Integer status) {
        Voucher voucher = voucherMapper.selectById(id);
        voucher.setStatus(status);
        voucherMapper.updateById(voucher);
        return R.ok().message(status == 0 ? "上架" : "下架");
    }

    //根据id获取优惠券信息
    @Override
    public R getVoucher(Long id) {
        Voucher voucher = voucherMapper.selectById(id);
        return R.ok().data("voucher", voucher);
    }
}
